#include "protocol.h"
#include <stdbool.h>

extern int socket_fd;
extern char mac_buf[6];
extern pthread_mutex_t protocol_mutex;
extern uint16_t enter_thread_time;
struct sockaddr_in* global_client_addr;
sqlite3 *fsl_db;
uint16_t tmp_seq = 0;
uint8_t on_off_state = 0;
bool url_requested = true;
bool url_file_Parse_Finish = false;
char *url_filename = NULL;
Device *device_list_array = NULL;
int device_list_count = 0;
Scene *scene_list_array = NULL;
int scene_list_count = 0;
FamilyInfo family_info;


void FSL_Set_Light_Switch_State(uint8_t on_off)
{
    on_off_state = on_off;
}

uint8_t FSL_Get_Light_Switch_State(void)
{
    return on_off_state;
}

void FSL_Set_Url_Requested_Flag(bool m_url_requested)
{
    url_requested = m_url_requested;
}

bool FSL_Get_Url_Requested_Flag(void)
{
    return url_requested;
}

void FSL_Set_Url_File_Parse_Finish_Flag(bool flag)
{
    url_file_Parse_Finish = flag;
}

bool FSL_Get_Url_File_Parse_Finish_Flag(void)
{
    return url_file_Parse_Finish;
}


// 开关灯全部
void FSL_All_Light_On_Off(uint16_t Seq, struct sockaddr_in* client_addr, bool on_off, uint8_t brightness)
{
    // if(device_list_array)
    // {
    //     for(int i; i < device_list_count; i++)
    //     {
    //         // 如果该数组不为空，证明是STA，而不是网关
    //         if(strlen(device_list_array[i].shortaddr) != 0)
    //         {
    //             FSL_Short_Adress_Control(Seq, client_addr, (uint16_t)atoi(device_list_array[i].shortaddr), on_off, brightness);
    //             // 更新本地状态
    //             device_list_array[i].CF_OnOff = on_off;
    //         }
    //     }
    // }

    for(uint16_t i = 0; i < sqlite3_check_table_columns(fsl_db, Device_List_Table); i++)
    {
            char sql[128];
            sprintf(sql, "SELECT shortaddr FROM %s LIMIT 1 OFFSET %d;", Device_List_Table, i);
            
            sqlite3_stmt *stmt;
            int rc = sqlite3_prepare_v2(fsl_db, sql, -1, &stmt, NULL);
            if (rc != SQLITE_OK) 
            {
                fprintf(stderr, "Failed to prepare statement: %s\n", sqlite3_errmsg(fsl_db));
                return;
            }

            if (sqlite3_step(stmt) == SQLITE_ROW) 
            {
                const char *shortaddr = (const char *)sqlite3_column_text(stmt, 0);
                FSL_Short_Adress_Control(Seq, client_addr, (uint16_t)atoi(shortaddr), on_off, brightness);

                // 更新数据库 CF_OnOff
                sprintf(sql, "UPDATE %s SET CF_OnOff = %d WHERE shortaddr = '%s';", Device_List_Table, on_off, shortaddr);
                sqlite3_exec(fsl_db, sql, 0, 0, 0);
            }

            sqlite3_finalize(stmt);
    }
}

// 清空数组
void FSL_Clear_Device_list()
{
    if(device_list_array)
    {
        free(device_list_array);
        device_list_count = 0;
    }
}

void FSL_Clear_Sence_list()
{
    if(scene_list_array)
    {
        free(scene_list_array);
        scene_list_count = 0;
    }
}

void FSL_Clear_Family_Info()
{
    if(family_info.roomlist_array)
    {
        free(family_info.roomlist_array);
        family_info.roomlist_array_count = 0;
        memset(&family_info, 0, sizeof(family_info));
    }
}

// 去除一个数组中的“0”
void remove_zeros(char *input, char *output) 
{
    while (*input == '0') 
    {
        input++;
    }
    strcpy(output, input);
}


// 回调函数，用于写入文件
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) 
{
    return fwrite(ptr, size, nmemb, stream);
}


// 根据短地址查找对应的 bletoken,并取出最后两位合并成char
char get_bletoken_last_byte(sqlite3 *db, uint16_t short_adress) 
{
    if (db == NULL) 
    {
        FSL_LOG("[get_bletoken_last_byte] Database handle is NULL");
        return 0;
    }

    char last_byte;
    sqlite3_stmt *stmt;
    const char *sql = "SELECT bletoken FROM sta_device WHERE shortaddr = ?";
    int rc;

    char short_adress_str[6];

    snprintf(short_adress_str, sizeof(short_adress_str), "%u", short_adress);

    rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) 
    {
        fprintf(stderr, "Failed to prepare statement: %s\n", sqlite3_errmsg(db));
        return -1;
    }

    sqlite3_bind_text(stmt, 1, short_adress_str, -1, SQLITE_STATIC);

    if (sqlite3_step(stmt) == SQLITE_ROW) 
    {
        const unsigned char *bletoken = sqlite3_column_text(stmt, 0);

        if (bletoken != NULL) 
        {
            int len = strlen((const char *)bletoken);
            if (len >= 2)
            {
                char last_two_chars[3]; // +1 for null terminator
                last_two_chars[0] = bletoken[len - 2];
                last_two_chars[1] = bletoken[len - 1];
                last_two_chars[2] = '\0';

                last_byte = (char)strtol(last_two_chars, NULL, 16);
            }
        }
    }

    sqlite3_finalize(stmt);

    return last_byte;
}

int base64_decode(char *input, cJSON **root) 
{
    BIO *bio, *b64;

    // 计算解码后数据的长度
    int input_len = strlen(input);
    int decode_len = (input_len + 2) / 4 * 3;
    char *buffer = (char *)malloc(decode_len);

    // 创建 BIO 对象
    bio = BIO_new_mem_buf(input, input_len);
    b64 = BIO_new(BIO_f_base64());
    bio = BIO_push(b64, bio);

    // 禁止换行符
    BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);

    // 读取数据
    int len = BIO_read(bio, buffer, input_len);
    BIO_free_all(bio);

    // 解析数据到 cJSON 对象
    *root = cJSON_Parse(buffer);

    // 释放缓冲区
    free(buffer);

    return len;
}

// 打开数据库连接
void sqlite3_open_database(sqlite3 **db) 
{
    int rc = sqlite3_open("fsl_database.db", db);
    if (rc) 
    {
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(*db));
    }
}

// 关闭数据库连接
void sqlite3_close_database(sqlite3 *db) 
{
    sqlite3_close(db);
}

// 创建表格
void sqlite3_create_table(sqlite3 *db) 
{
    // STA设备
char *sql = "CREATE TABLE IF NOT EXISTS sta_device ("
                "did TEXT, "
                "pid TEXT, "
                "devicetypeflag INT, "
                "blecatetory TEXT, "
                "spid TEXT, "
                "devname TEXT, "
                "room TEXT, "
                "roomId INT, "
                "bletoken TEXT, "
                "aeskey TEXT, "
                "terminalid INT, "
                "ignoreflag INT, "
                "extendInfo TEXT, "
                "shortaddr TEXT, "
                "sdid TEXT, "
                "CF_RadarOnOff INT, "
                "CF_BrightH INT, "
                "CF_BrightHDelay INT, "
                "CF_BrightM INT, "
                "CF_BrightMDelay INT, "
                "CF_BrightL INT,"
                    "CF_DeviceId TEXT,"         // 下面开始就是新增的
                    "CF_DeviceName TEXT,"
                    "CF_ProductId TEXT,"
                    "CF_ProjectId TEXT,"
                    "CF_SpaceId TEXT,"
                    "CF_RegionId TEXT,"
                    "CF_GroupIds TEXT,"         // 使用JSON字符串存储数组
                    "CF_EnergyCost TEXT,"
                    "CF_CurrentEnergyCost TEXT,"
                    "CF_EnergyCostDict TEXT,"
                    "CF_Power INT,"
                    "CF_WorkDuration INT,"
                    "CF_Mac TEXT,"
                    "CF_Version TEXT,"
                    "CF_OnOff INT,"
                    "CF_Flash TEXT,"
                    "CF_Bright INT,"
                    "CF_RadarBrightSetting TEXT,"
                    "CF_RadarTimerOnOff TEXT,"
                    "CF_RadarTimerSetting TEXT,"
                    "CF_GatewayId TEXT,"
                    "CF_TriggerCount TEXT,"
                    "CF_LastUpdateTime TEXT,"
                    "CF_ReportTime TEXT"
                ");";
    int rc = sqlite3_exec(db, sql, 0, 0, 0);
    if (rc != SQLITE_OK) 
    {
        fprintf(stderr, "Sta Device Table SQL error: %s\n", sqlite3_errmsg(db));
    }

    // 网关表
    sql = "CREATE TABLE IF NOT EXISTS gateway ("
                "did TEXT, "
                "devname TEXT, "
                "room TEXT, "
                "pid TEXT, "
                "aeskey TEXT, "
                "version TEXT, "
                "extendInfo TEXT, "
                "devicetypeflag INT, "
                "terminalid INT, "
                "ignoreflag INT, "
                "roomId INT"
                ");";

    rc = sqlite3_exec(db, sql, 0, 0, 0);
    if (rc != SQLITE_OK) 
    {
        fprintf(stderr, "gateway Table SQL error: %s\n", sqlite3_errmsg(db));
    }

    // 场景( Scene )
    sql = "CREATE TABLE IF NOT EXISTS scene ("
            "moduledev_sdid TEXT, "
            "moduledev_content TEXT, "
            "moduledev_did TEXT, "
            "name TEXT, "
            "roomId INT, "
            "image TEXT, "
            "backColor INT, "
            "room TEXT, "
            "bletoken TEXT, "
            "moduleid TEXT, "
            "ignoreflag INT"
            ");";

    rc = sqlite3_exec(db, sql, 0, 0, 0);
    if (rc != SQLITE_OK) 
    {
        fprintf(stderr, "Scene Table SQL error: %s\n", sqlite3_errmsg(db));
    }

}


// 计算一个表里面有几行成员
uint16_t sqlite3_check_table_columns(sqlite3 *db, const char *table_name)
{
    char sql[256];
    sprintf(sql, "SELECT COUNT(*) FROM %s;", table_name);
    
    sqlite3_stmt *stmt;
    uint16_t row_count = 0;
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);

    if (rc != SQLITE_OK) 
    {
        fprintf(stderr, "[sqlite3_check_table_columns]Failed to prepare statement: %s\n", sqlite3_errmsg(db));
        return 0;
    }

    rc = sqlite3_step(stmt);
    if (rc == SQLITE_ROW) 
    {
        row_count = (uint16_t)sqlite3_column_int(stmt, 0);
    } else {
        fprintf(stderr, "[sqlite3_check_table_columns]Failed to execute statement: %s\n", sqlite3_errmsg(db));
    }

    sqlite3_finalize(stmt);
    return row_count;
}


// 插入设备数据到数据库
/*
    sdid = CF_DeviceId
    devname = CF_DeviceName
*/
void sqlite3_insert_device(Device device, sqlite3 *db)
{
    char sql[2048];
    sprintf(sql, "SELECT * FROM sta_device WHERE shortaddr='%s';", device.shortaddr);
    
    // 造轮子，开始堆切CF_**的变量
    char CF_DeviceId[16] = {};
    remove_zeros(device.sdid, CF_DeviceId);

    // 执行查询
    sqlite3_stmt *stmt;
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) 
    {
        fprintf(stderr, "[sqlite3_insert_device]sqlite3_prepare_v2 SQL error: %s\n", sqlite3_errmsg(db));
    }

    // 检查查询结果
    if (sqlite3_step(stmt) == SQLITE_ROW) 
    {
        // 数据已存在，执行更新操作
        // sprintf(sql, "UPDATE sta_device SET pid='%s', CF_DeviceId='%s', devicetypeflag=%d, blecatetory='%s', spid='%s', CF_DeviceName='%s', room='%s', roomId=%d, bletoken='%s', aeskey='%s', terminalid=%d, ignoreflag=%d, CF_Version='%s', extendInfo='%s', shortaddr='%s', sdid='%s', switch_status=%d WHERE did='%s' AND sdid='%s';",
        //     device.pid, CF_DeviceId, device.devicetypeflag, device.blecatetory, device.spid, device.devname, device.room, device.roomId, device.bletoken, device.aeskey, device.terminalid ? 1 : 0, device.ignoreflag, device.version, device.extendInfo, device.shortaddr, device.sdid, device.switch_status ? 1 : 0, device.did, device.sdid);
        sprintf(sql, "UPDATE sta_device SET pid='%s', CF_DeviceId='%s', devicetypeflag=%d, blecatetory='%s', spid='%s', CF_DeviceName='%s', room='%s', roomId=%d, bletoken='%s', aeskey='%s', terminalid=%d, ignoreflag=%d, CF_Version='%s', extendInfo='%s', shortaddr='%s', sdid='%s', CF_OnOff=%d;",
            device.pid, CF_DeviceId, device.devicetypeflag, device.blecatetory, device.spid, device.devname, device.room, device.roomId, device.bletoken, device.aeskey, device.terminalid ? 1 : 0, device.ignoreflag, device.version, device.extendInfo, device.shortaddr, device.sdid, device.CF_OnOff ? 1 : 0);

        FSL_LOG("短地址 %s 数据已存在，执行更新操作", device.shortaddr);
    }
    else
    {
        // 数据不存在，执行插入操作
        sprintf(sql, "INSERT INTO sta_device (did, pid, devicetypeflag, blecatetory, spid, CF_DeviceName, room, roomId, bletoken, aeskey, terminalid, ignoreflag, CF_Version, extendInfo, shortaddr, sdid, CF_OnOff, CF_DeviceId, CF_Power) VALUES ('%s', '%s', %d, '%s', '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s', %d, '%s', %d);",
            device.did, device.pid, device.devicetypeflag, device.blecatetory, device.spid, device.devname, device.room, device.roomId, device.bletoken, device.aeskey, device.terminalid ? 1 : 0, device.ignoreflag, device.version, device.extendInfo, device.shortaddr, device.sdid, device.CF_OnOff ? 1 : 0, CF_DeviceId, 16);
        
        FSL_LOG("短地址 %s 数据不存在，执行更新操作", device.shortaddr);
    }

    // 执行更新或插入操作
    rc = sqlite3_exec(db, sql, 0, 0, 0);
    if (rc != SQLITE_OK) 
    {
        fprintf(stderr, "[sqlite3_insert_device] sqlite3_exec SQL error: %s\n", sqlite3_errmsg(db));
    }

    // 释放查询结果
    sqlite3_finalize(stmt);
}

// 插入数据到网关的表
/*
    网关的did = 每个子设备的CF_GatewayId
*/
void sqlite3_insert_gateway(Device device, sqlite3 *db)
{
    char sql[1024];
    sprintf(sql, "SELECT * FROM gateway WHERE did='%s';", device.did);

    // 执行查询
    sqlite3_stmt *stmt;
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, "sqlite3_prepare_v2 SQL error: %s\n", sqlite3_errmsg(db));
        return;
    }

    // 检查查询结果
    if (sqlite3_step(stmt) == SQLITE_ROW)
    {
        // 数据已存在，执行更新操作
        sprintf(sql, "UPDATE gateway SET devname='%s', room='%s', pid='%s', aeskey='%s', version='%s', extendInfo='%s', devicetypeflag=%d, terminalid=%d, ignoreflag=%d, roomId=%d WHERE did='%s';",
                device.devname, device.room, device.pid, device.aeskey[0] ? device.aeskey : "", device.version, device.extendInfo, device.devicetypeflag, device.terminalid, device.ignoreflag ? 1 : 0, device.roomId, device.did);

        FSL_LOG("网关ID %s 数据已存在，执行更新操作", device.did);
    }
    else
    {
        // 数据不存在，执行插入操作
        sprintf(sql, "INSERT INTO gateway (did, devname, room, pid, aeskey, version, extendInfo, devicetypeflag, terminalid, ignoreflag, roomId) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d);",
                device.did, device.devname, device.room, device.pid, device.aeskey[0] ? device.aeskey : "", device.version, device.extendInfo, device.devicetypeflag, device.terminalid, device.ignoreflag ? 1 : 0, device.roomId);

        FSL_LOG("网关ID %s 数据不存在，执行插入操作", device.did);
    }

    // 执行更新或插入操作
    rc = sqlite3_exec(db, sql, 0, 0, 0);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, "[sqlite3_insert_gateway] sqlite3_exec SQL error: %s\n", sqlite3_errmsg(db));
    }

    // 释放查询结果
    sqlite3_finalize(stmt);
}


void sqlite3_insert_scene(Scene scene, sqlite3 *db)
{
    char sql[1024];
    sprintf(sql, "SELECT * FROM scene WHERE moduleid='%s';", scene.moduleid);
    
    // 执行查询
    sqlite3_stmt *stmt;
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, "[sqlite3_insert_scene]sqlite3_prepare_v2 SQL error: %s\n", sqlite3_errmsg(db));
        return;
    }

    // 检查查询结果
    if (sqlite3_step(stmt) == SQLITE_ROW)
    {
        // 数据已存在，执行更新操作
        sprintf(sql, "UPDATE scene SET moduledev_sdid='%s', moduledev_content='%s', moduledev_did='%s', name='%s', roomId=%d, image='%s', backColor=%d, room='%s', bletoken='%s', ignoreflag=%d WHERE moduleid='%s';",
                scene.moduledev_sdid, scene.moduledev_content, scene.moduledev_did, scene.name, scene.roomId, scene.image, scene.backColor, scene.room, scene.bletoken, scene.ignoreflag ? 1 : 0, scene.moduleid);

        FSL_LOG("Module ID %s 数据已存在，执行更新操作", scene.moduleid);
    }
    else
    {
        // 数据不存在，执行插入操作
        sprintf(sql, "INSERT INTO scene (moduledev_sdid, moduledev_content, moduledev_did, name, roomId, image, backColor, room, bletoken, moduleid, ignoreflag) VALUES ('%s', '%s', '%s', '%s', %d, '%s', %d, '%s', '%s', '%s', %d);",
                scene.moduledev_sdid, scene.moduledev_content, scene.moduledev_did, scene.name, scene.roomId, scene.image, scene.backColor, scene.room, scene.bletoken, scene.moduleid, scene.ignoreflag ? 1 : 0);

        FSL_LOG("Module ID %s 数据不存在，执行插入操作", scene.moduleid);
    }

    // 执行更新或插入操作
    rc = sqlite3_exec(db, sql, 0, 0, 0);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, "[sqlite3_insert_scene] sqlite3_exec SQL error: %s\n", sqlite3_errmsg(db));
    }

    // 释放查询结果
    sqlite3_finalize(stmt);
}



// void Process_Devlist(cJSON *item)
// {
//     // 获取 data 字段的值
//     cJSON *data = cJSON_GetObjectItemCaseSensitive(item, "data");
//     if (!cJSON_IsString(data)) 
//     {
//         FSL_LOG("Error: data is not a string.\n");
//         return;
//     }
//     base64_decode(data->valuestring, &data);
//     if(data)
//     {
//         // printf("[Decoded] datalist size is %d\n", cJSON_GetArraySize(data));
//         // printf("Decoded JSON:\n%s\n", cJSON_Print(data));
//         device_list_count = cJSON_GetArraySize(data);
//         device_list_array = (Device *)malloc(device_list_count * sizeof(Device));
//         memset(device_list_array, 0, device_list_count * sizeof(Device));

//         for(int i = 0; i < device_list_count; i++)
//         {
//             cJSON *device = cJSON_GetArrayItem(data, i);
//             if (device == NULL) 
//             {
//                 FSL_LOG("Error getting device from array.\n");
//                 continue;
//             }

//             // 检查是否包含 blecatetory 键
//             cJSON *blecatetory = cJSON_GetObjectItemCaseSensitive(device, "blecatetory");
//             // 如果没有 “blecatetory”，那这个设备就是网关，反之就是其他子设备
//             if (blecatetory != NULL) 
//             {
//                 // 从 JSON 对象中获取键值对并保存到结构体中
//                 strcpy(device_list_array[i].did, cJSON_GetObjectItemCaseSensitive(device, "did")->valuestring);
//                 strcpy(device_list_array[i].pid, cJSON_GetObjectItemCaseSensitive(device, "pid")->valuestring);
//                 device_list_array[i].devicetypeflag = cJSON_GetObjectItemCaseSensitive(device, "devicetypeflag")->valueint;
//                 strcpy(device_list_array[i].blecatetory, cJSON_GetObjectItemCaseSensitive(device, "blecatetory")->valuestring);
//                 strcpy(device_list_array[i].spid, cJSON_GetObjectItemCaseSensitive(device, "spid")->valuestring);
//                 strcpy(device_list_array[i].devname, cJSON_GetObjectItemCaseSensitive(device, "devname")->valuestring);
//                 strcpy(device_list_array[i].room, cJSON_GetObjectItemCaseSensitive(device, "room")->valuestring);
//                 device_list_array[i].roomId = cJSON_GetObjectItemCaseSensitive(device, "roomId")->valueint;
//                 strcpy(device_list_array[i].bletoken, cJSON_GetObjectItemCaseSensitive(device, "bletoken")->valuestring);
//                 device_list_array[i].ignoreflag = cJSON_IsFalse(cJSON_GetObjectItemCaseSensitive(device, "ignoreflag")) ? 0 : 1;
//                 strcpy(device_list_array[i].version, cJSON_GetObjectItemCaseSensitive(device, "version")->valuestring);
//                 strcpy(device_list_array[i].extendInfo, cJSON_GetObjectItemCaseSensitive(device, "extendInfo")->valuestring);
//                 strcpy(device_list_array[i].shortaddr, cJSON_GetObjectItemCaseSensitive(device, "shortaddr")->valuestring);
//                 strcpy(device_list_array[i].sdid, cJSON_GetObjectItemCaseSensitive(device, "sdid")->valuestring);
//             } 
//             else    // 网关
//             {
//                 // 将 JSON 中的值赋给结构体成员
//                 strcpy(device_list_array[i].did, cJSON_GetObjectItemCaseSensitive(device, "did")->valuestring);
//                 strcpy(device_list_array[i].devname, cJSON_GetObjectItemCaseSensitive(device, "devname")->valuestring);
//                 strcpy(device_list_array[i].room, cJSON_GetObjectItemCaseSensitive(device, "room")->valuestring);
//                 device_list_array[i].devicetypeflag = cJSON_GetObjectItemCaseSensitive(device, "devicetypeflag")->valueint;
//                 strcpy(device_list_array[i].pid, cJSON_GetObjectItemCaseSensitive(device, "pid")->valuestring);
//                 // 如果 aeskey 是字符串，使用 strcpy 复制到结构体中，如果是 null，需要采取特殊处理
//                 if (cJSON_IsString(cJSON_GetObjectItemCaseSensitive(device, "aeskey"))) {
//                     strcpy(device_list_array[i].aeskey, cJSON_GetObjectItemCaseSensitive(device, "aeskey")->valuestring);
//                 } else {
//                     // 特殊处理，例如赋予一个默认值
//                     strcpy(device_list_array[i].aeskey, "default_aeskey");
//                 }
//                 device_list_array[i].terminalid = cJSON_GetObjectItemCaseSensitive(device, "terminalid")->valueint;
//                 device_list_array[i].ignoreflag = cJSON_IsFalse(cJSON_GetObjectItemCaseSensitive(device, "ignoreflag")) ? 0 : 1;
//                 strcpy(device_list_array[i].version, cJSON_GetObjectItemCaseSensitive(device, "version")->valuestring);
//                 strcpy(device_list_array[i].extendInfo, cJSON_GetObjectItemCaseSensitive(device, "extendInfo")->valuestring);
//                 device_list_array[i].roomId = cJSON_GetObjectItemCaseSensitive(device, "roomId")->valueint;

//             }

//         }
//     }
// }


void Process_Devlist(cJSON *item)
{
    // 获取 data 字段的值
    cJSON *data = cJSON_GetObjectItemCaseSensitive(item, "data");
    if (!cJSON_IsString(data)) 
    {
        FSL_LOG("Error: data is not a string.\n");
        return;
    }
    base64_decode(data->valuestring, &data);
    if(data)
    {
        for(int i = 0; i < cJSON_GetArraySize(data); i++)
        {
            cJSON *device = cJSON_GetArrayItem(data, i);
            if (device == NULL) 
            {
                FSL_LOG("Error getting device from array.\n");
                continue;
            }

            // 检查是否包含 blecatetory 键
            cJSON *blecatetory = cJSON_GetObjectItemCaseSensitive(device, "blecatetory");
            // 如果没有 “blecatetory”，那这个设备就是网关，反之就是其他子设备
            if (blecatetory != NULL) 
            {
                Device new_device;
                strcpy(new_device.did, cJSON_GetObjectItemCaseSensitive(device, "did")->valuestring);
                strcpy(new_device.pid, cJSON_GetObjectItemCaseSensitive(device, "pid")->valuestring);
                new_device.devicetypeflag = cJSON_GetObjectItemCaseSensitive(device, "devicetypeflag")->valueint;
                strcpy(new_device.blecatetory, cJSON_GetObjectItemCaseSensitive(device, "blecatetory")->valuestring);
                strcpy(new_device.spid, cJSON_GetObjectItemCaseSensitive(device, "spid")->valuestring);
                strcpy(new_device.devname, cJSON_GetObjectItemCaseSensitive(device, "devname")->valuestring);
                strcpy(new_device.room, cJSON_GetObjectItemCaseSensitive(device, "room")->valuestring);
                new_device.roomId = cJSON_GetObjectItemCaseSensitive(device, "roomId")->valueint;
                strcpy(new_device.bletoken, cJSON_GetObjectItemCaseSensitive(device, "bletoken")->valuestring);
                new_device.ignoreflag = cJSON_IsFalse(cJSON_GetObjectItemCaseSensitive(device, "ignoreflag")) ? 0 : 1;
                strcpy(new_device.version, cJSON_GetObjectItemCaseSensitive(device, "version")->valuestring);
                strcpy(new_device.extendInfo, cJSON_GetObjectItemCaseSensitive(device, "extendInfo")->valuestring);
                strcpy(new_device.shortaddr, cJSON_GetObjectItemCaseSensitive(device, "shortaddr")->valuestring);
                strcpy(new_device.sdid, cJSON_GetObjectItemCaseSensitive(device, "sdid")->valuestring);

                // 插入数据到数据库
                sqlite3_insert_device(new_device, fsl_db);
            } 
            else    // 网关
            {
                // 将 JSON 中的值赋给结构体成员
                char temp[20] = {};
                Device new_device;
                // did
                strcpy(new_device.did, cJSON_GetObjectItemCaseSensitive(device, "did")->valuestring);
                remove_zeros(new_device.did, temp);
                memset(new_device.did, 0, sizeof(new_device.did));
                strcpy(new_device.did, temp);
                // devname
                strcpy(new_device.devname, cJSON_GetObjectItemCaseSensitive(device, "devname")->valuestring);
                // room
                strcpy(new_device.room, cJSON_GetObjectItemCaseSensitive(device, "room")->valuestring);
                new_device.devicetypeflag = cJSON_GetObjectItemCaseSensitive(device, "devicetypeflag")->valueint;
                // pid
                strcpy(new_device.pid, cJSON_GetObjectItemCaseSensitive(device, "pid")->valuestring);
                memset(temp, 0, sizeof(temp));
                remove_zeros(new_device.pid, temp);
                memset(new_device.pid, 0, sizeof(new_device.pid));
                strcpy(new_device.pid, temp);
                // 如果 aeskey 是字符串，使用 strcpy 复制到结构体中，如果是 null，需要采取特殊处理
                if (cJSON_IsString(cJSON_GetObjectItemCaseSensitive(device, "aeskey"))) 
                {
                    strcpy(new_device.aeskey, cJSON_GetObjectItemCaseSensitive(device, "aeskey")->valuestring);
                }
                else
                {
                    // 特殊处理，例如赋予一个默认值
                    strcpy(new_device.aeskey, "default_aeskey");
                }
                new_device.terminalid = cJSON_GetObjectItemCaseSensitive(device, "terminalid")->valueint;
                new_device.ignoreflag = cJSON_IsFalse(cJSON_GetObjectItemCaseSensitive(device, "ignoreflag")) ? 0 : 1;
                strcpy(new_device.version, cJSON_GetObjectItemCaseSensitive(device, "version")->valuestring);
                strcpy(new_device.extendInfo, cJSON_GetObjectItemCaseSensitive(device, "extendInfo")->valuestring);
                new_device.roomId = cJSON_GetObjectItemCaseSensitive(device, "roomId")->valueint;

                sqlite3_insert_gateway(new_device, fsl_db);
            }
        }
    }
}



// void Process_Scenelist(cJSON *item)
// {
//     cJSON *data = cJSON_GetObjectItemCaseSensitive(item, "data");
//     if (!cJSON_IsString(data)) 
//     {
//         FSL_LOG("Error: data is not a string.\n");
//         return;
//     }
//     base64_decode(data->valuestring, &data);
//     if(data)
//     {
//         scene_list_count = cJSON_GetArraySize(data);
//         scene_list_array = (Scene *)malloc(scene_list_count * sizeof(Scene));
//         memset(scene_list_array, 0, scene_list_count * sizeof(Scene));


//         for(int i = 0; i < scene_list_count; i++)
//         {
//             cJSON *scene_data = cJSON_GetArrayItem(data, i);
//             if (scene_data == NULL) 
//             {
//                 FSL_LOG("Error getting scene_data from array.\n");
//                 continue;
//             }

//             cJSON *moduledev_array = cJSON_GetObjectItemCaseSensitive(scene_data, "moduledev");
//             if (!cJSON_IsArray(moduledev_array)) 
//             {
//                 FSL_LOG("Error: moduledev is not an array.\n");
//                 continue;
//             }

//             // 处理每个 moduledev 对象
//             cJSON *moduledev = cJSON_GetArrayItem(moduledev_array, 0); // 假设每个场景只有一个 moduledev 对象
//             if(moduledev != NULL)
//             {
//                 strcpy(scene_list_array[i].sdid, cJSON_GetObjectItemCaseSensitive(moduledev, "sdid")->valuestring);
//                 strcpy(scene_list_array[i].content, cJSON_GetObjectItemCaseSensitive(moduledev, "content")->valuestring);
//                 strcpy(scene_list_array[i].did, cJSON_GetObjectItemCaseSensitive(moduledev, "did")->valuestring);
//                 strcpy(scene_list_array[i].name, cJSON_GetObjectItemCaseSensitive(scene_data, "name")->valuestring);
//                 scene_list_array[i].roomId = cJSON_GetObjectItemCaseSensitive(scene_data, "roomId")->valueint;
//                 strcpy(scene_list_array[i].image, cJSON_GetObjectItemCaseSensitive(scene_data, "image")->valuestring);
//                 scene_list_array[i].backColor = cJSON_GetObjectItemCaseSensitive(scene_data, "backColor")->valueint;
//                 strcpy(scene_list_array[i].room, cJSON_GetObjectItemCaseSensitive(scene_data, "room")->valuestring);
//                 strcpy(scene_list_array[i].bletoken, cJSON_GetObjectItemCaseSensitive(scene_data, "bletoken")->valuestring);
//                 strcpy(scene_list_array[i].moduleid, cJSON_GetObjectItemCaseSensitive(scene_data, "moduleid")->valuestring);
//                 scene_list_array[i].ignoreflag = cJSON_IsFalse(cJSON_GetObjectItemCaseSensitive(scene_data, "ignoreflag")) ? false : true;
//             }
//         }
//     }
// }

void Process_Scenelist(cJSON *item)
{
    cJSON *data = cJSON_GetObjectItemCaseSensitive(item, "data");
    if (!cJSON_IsString(data)) 
    {
        FSL_LOG("Error: data is not a string.\n");
        return;
    }
    base64_decode(data->valuestring, &data);
    if(data)
    {
        // scene_list_count = cJSON_GetArraySize(data);
        // scene_list_array = (Scene *)malloc(scene_list_count * sizeof(Scene));
        // memset(scene_list_array, 0, scene_list_count * sizeof(Scene));


        for(int i = 0; i < cJSON_GetArraySize(data); i++)
        {
            cJSON *scene_data = cJSON_GetArrayItem(data, i);
            if (scene_data == NULL) 
            {
                FSL_LOG("Error getting scene_data from array.\n");
                continue;
            }

            cJSON *moduledev_array = cJSON_GetObjectItemCaseSensitive(scene_data, "moduledev");
            if (!cJSON_IsArray(moduledev_array)) 
            {
                FSL_LOG("Error: moduledev is not an array.\n");
                continue;
            }

            // 处理每个 moduledev 对象
            cJSON *moduledev = cJSON_GetArrayItem(moduledev_array, 0); // 假设每个场景只有一个 moduledev 对象
            if(moduledev != NULL)
            {
                Scene scene;
                strcpy(scene.moduledev_sdid, cJSON_GetObjectItemCaseSensitive(moduledev, "sdid")->valuestring);
                strcpy(scene.moduledev_content, cJSON_GetObjectItemCaseSensitive(moduledev, "content")->valuestring);
                strcpy(scene.moduledev_did, cJSON_GetObjectItemCaseSensitive(moduledev, "did")->valuestring);
                strcpy(scene.name, cJSON_GetObjectItemCaseSensitive(scene_data, "name")->valuestring);
                scene.roomId = cJSON_GetObjectItemCaseSensitive(scene_data, "roomId")->valueint;
                strcpy(scene.image, cJSON_GetObjectItemCaseSensitive(scene_data, "image")->valuestring);
                scene.backColor = cJSON_GetObjectItemCaseSensitive(scene_data, "backColor")->valueint;
                strcpy(scene.room, cJSON_GetObjectItemCaseSensitive(scene_data, "room")->valuestring);
                strcpy(scene.bletoken, cJSON_GetObjectItemCaseSensitive(scene_data, "bletoken")->valuestring);
                strcpy(scene.moduleid, cJSON_GetObjectItemCaseSensitive(scene_data, "moduleid")->valuestring);
                scene.ignoreflag = cJSON_IsFalse(cJSON_GetObjectItemCaseSensitive(scene_data, "ignoreflag")) ? false : true;

                sqlite3_insert_scene(scene, fsl_db);
            }
        }
    }
}


void Process_FamilyInfo(cJSON *item)
{
    cJSON *data = cJSON_GetObjectItemCaseSensitive(item, "data");
    if (!cJSON_IsString(data)) 
    {
        FSL_LOG("Error: data is not a string.\n");
        return;
    }
    base64_decode(data->valuestring, &data);
    if(data)
    {
        // 抓取 “roomlist” 数组的成员
        cJSON *roomlist_array = cJSON_GetObjectItem(data, "roomlist");
        if (roomlist_array != NULL) 
        {
            family_info.roomlist_array_count = cJSON_GetArraySize(roomlist_array);
            family_info.roomlist_array = (Room *)malloc(family_info.roomlist_array_count * sizeof(Room));
            memset(family_info.roomlist_array, 0, family_info.roomlist_array_count * sizeof(Room));
            
            int index = 0;
            cJSON *room = NULL;
            cJSON_ArrayForEach(room, roomlist_array) 
            {
                cJSON *roomId = cJSON_GetObjectItem(room, "roomId");
                cJSON *roomName = cJSON_GetObjectItem(room, "roomName");
                if (roomId != NULL && roomName != NULL)
                {
                    family_info.roomlist_array[index].roomId = roomId->valueint;
                    strcpy(family_info.roomlist_array[index].roomName, roomName->valuestring);
                    index++;
                }
            }
        }

        cJSON *name = cJSON_GetObjectItem(data, "name");
        if (name != NULL) {
            strcpy(family_info.name, name->valuestring);
        }

        cJSON *updateTime = cJSON_GetObjectItem(data, "updateTime");
        if (updateTime != NULL) {
            family_info.updateTime = updateTime->valueint;
        }

        cJSON *familyId = cJSON_GetObjectItem(data, "familyId");
        if (familyId != NULL) {
            strcpy(family_info.familyId, familyId->valuestring);
        }

    }
}


// 解析.bat文件，并用base64 解密
int FSL_Parse_Url_File(void)
{
    // FSL_LOG("%s", url_filename);
    FILE *fp = fopen(url_filename, "r");
    if (fp == NULL) 
    {
        FSL_LOG("Error opening file.");
        return 1;
    }

    // 读取文件内容
    fseek(fp, 0, SEEK_END);
    long file_size = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    char *json_string = (char *)malloc(file_size + 1);
    if (json_string == NULL) 
    {
        printf("Error allocating memory.\n");
        fclose(fp);
        return 1;
    }

    fread(json_string, 1, file_size, fp);
    json_string[file_size] = '\0';
    fclose(fp);

    // 解析 JSON 字符串
    cJSON *root = cJSON_Parse(json_string);
    if (root == NULL) 
    {
        printf("Error parsing JSON: %s\n", cJSON_GetErrorPtr());
        free(json_string);
        return 1;
    }
    free(json_string);

    // 获取 dataList 数组
    cJSON *dataList = cJSON_GetObjectItemCaseSensitive(root, "dataList");
    if (!cJSON_IsArray(dataList)) 
    {
        printf("Error: dataList is not an array.\n");
        cJSON_Delete(root);
        return 1;
    }

    // 获取 dataList 数组的大小
    int array_size = cJSON_GetArraySize(dataList);
    if (array_size <= 0) 
    {
        printf("Error: dataList array is empty or not an array.\n");
        cJSON_Delete(root);
        return 1;
    }
    // FSL_LOG("datalist size is %d", array_size);

    // 遍历 dataList 数组的每个元素
    cJSON *item;
    cJSON_ArrayForEach(item, dataList) 
    {
                // 获取 mtag 字段的值
        cJSON *mtag = cJSON_GetObjectItemCaseSensitive(item, "mtag");
        if (!cJSON_IsString(mtag)) 
        {
            FSL_LOG("Error: mtag is not a string.\n");
            continue; // 跳过此元素
        }
        else
        {   
            // 如果是 devlist
            if(strcmp(mtag->valuestring, "devlist") == 0)
            {
                Process_Devlist(item);
            }
            else if(strcmp(mtag->valuestring, "scenelist") == 0)
            {
                Process_Scenelist(item);
            }
            else if(strcmp(mtag->valuestring, "familyInfo") == 0)
            {
                Process_FamilyInfo(item);
            }
        }
    }

    FSL_Set_Url_File_Parse_Finish_Flag(true);
    // 释放 cJSON 对象
    cJSON_Delete(root);

    return 0;
}


//发送协议数据
size_t FSL_UDP_SendData(int fd, const void *__buf, size_t length, int __flags, 
                struct sockaddr_in* client_addr,
		       socklen_t __addr_len)
{
    if(sendto(fd, __buf, length, __flags, (struct sockaddr *)client_addr, __addr_len) == -1)
    {
        perror("sendto");
        return 256;
    }
    else
    {
        printf("Send to Client IP: %s, Port: %d\n", inet_ntoa(client_addr->sin_addr), ntohs(client_addr->sin_port));
        return length;
    }
    
}

// 处理帧头的函数
void FSL_Handle_Protocol_head(uint16_t Type, uint16_t Seq, uint8_t *buf)
{
    // 前两行：举例：0x0400 拆分为0x04,0x00
    buf[0] = DWORD_BYTE_DIVIDE_H3(Type);
    buf[1] = DWORD_BYTE_DIVIDE_H4(Type);
    buf[2] = DWORD_BYTE_DIVIDE_H4(Seq);
    buf[3] = DWORD_BYTE_DIVIDE_H3(Seq);

}

// 【心跳响应】
void FSL_HearBeat_Response(uint16_t Seq, struct sockaddr_in* client_addr)
{
    uint16_t length = 10;
    uint8_t buf[length];

    FSL_Handle_Protocol_head(HearBeat_Response, Seq, buf);
    
    memcpy(buf+4, mac_buf, sizeof(mac_buf));

    // 该协议长度只需要10位
    if(FSL_UDP_SendData(socket_fd, buf, length, 0, client_addr, sizeof(struct sockaddr)) != 256)
    {
        printf("Send Buf: ");
        for(uint16_t i = 0; i < length; i++)
        {
            printf("%02X ", buf[i]);
        }
        printf("\n");
    }
}

// 【配置URL 请求数据】
void FSL_URL_Request(uint16_t  Seq, struct sockaddr_in* client_addr)
{
    printf("【请求URL数据】\n");
    uint16_t length = 4;
    uint8_t buf[length];

    FSL_Handle_Protocol_head(URL_Request, Seq, buf);
    if(FSL_UDP_SendData(socket_fd, buf, length, 0, client_addr, sizeof(struct sockaddr)) != 256)
    {
        printf("Send Buf: ");
        for(uint16_t i = 0; i < length; i++)
        {
            printf("%02X ", buf[i]);
        }
        printf("\n");
    }
}


// 【响应URL，开始下载URL文件】
int FSL_URL_Response( char *buf)
{
    char url_buf[50] = {};
    // char file_name_buf[20] = {};
    sprintf(url_buf, "%s", buf + 4);            // +4是为了把开头的Type和 Seq 都去掉

    FSL_LOG("url_buf = %s", url_buf);
    
    // 在 URL 中查找最后一个斜杠 '/'
    char *last_slash = strrchr(url_buf, '/');
    if (last_slash != NULL) 
    {
        // 指向文件名的下一个字符
        url_filename = (char *)malloc(strlen(last_slash + 1)); // 在堆上分配内存
        if (url_filename == NULL)
        {
            // 内存分配失败
            return -1;
        }
        strcpy(url_filename, last_slash + 1);
    }

    // 打印提取出的文件名
    // FSL_LOG("Filename: %s\n", filename);

    FILE *output_file = fopen(url_filename, "wb");
    if (!output_file) 
    {
        fprintf(stderr, "Error opening output file\n");
        return EXIT_FAILURE;
    }

    CURL *curl = curl_easy_init();
    if (curl) 
    {
        curl_easy_setopt(curl, CURLOPT_URL, url_buf);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, output_file);

        CURLcode res = curl_easy_perform(curl);
        if (res != CURLE_OK) 
        {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
            fclose(output_file);
            curl_easy_cleanup(curl);
            return EXIT_FAILURE;
        }

        curl_easy_cleanup(curl);
        fclose(output_file);
        FSL_LOG("File downloaded successfully.");
        return EXIT_SUCCESS;
    } 
    else 
    {
        fprintf(stderr, "Failed to initialize libcurl\n");
        fclose(output_file);
        return EXIT_FAILURE;
    }
}

// 【设置停车场感应器】
// "bletoken" 这个家庭key的最后两位
void FSL_Set_Park_Area_Sensor(uint16_t Seq, struct sockaddr_in* client_addr, uint16_t short_adress, 
                                uint8_t if_Group_control, char Group_id, uint8_t Sensor_Switch, 
                                uint8_t Brightness_H, uint16_t CF_BrightHDelay, uint8_t Brightness_Lowest,  
                                uint8_t Brightness_Middle, uint16_t Brightness_Middle_Delay_time)
{
    uint16_t length = 20;        // 这个协议只需要20个字节 
    uint8_t buf[length];
    static uint16_t m_Seq = 0;


    // 根据短地址查找对应的 bletoken ，并取出最后两位合并成char。
    char key = get_bletoken_last_byte(fsl_db, short_adress);


    FSL_Handle_Protocol_head(Park_Area_Sensor, Seq, buf);
    // (短地址255-511固定为d1，小于255为d0，512-767为d2)
    if(short_adress <= 255)
    {
        buf[4] = 0xd0;
    }
    else if(255 < short_adress && short_adress <= 511)
    {
        buf[4] = 0xd1;
    }
    else if( 512 <= short_adress && short_adress <= 767)
    {
        buf[4] = 0xd2;
    }
    buf[5] = m_Seq++;
    buf[6] = key;

    // 这两位是固定的，只有基于停车场感应灯是这样的，其他的类型会变
    buf[8] = 0x00;buf[9] = 0x5e;
    // 单设备控制就是0x00；基于分组的设置就是0x01
    if(if_Group_control)
        buf[10] = 0x01;
    else
        buf[10] = 0x00;

    // 短地址的低字节;如果是分组设置则为groupID
    if(if_Group_control)
        buf[11] = DWORD_BYTE_DIVIDE_H4(short_adress);
    else
        buf[11] = Group_id;
    
    // 雷达感应开关，0表示关；1表示开
    buf[12] = Sensor_Switch;

    // 全亮模式的亮度值，亮度值为0-127对应0-100%（同灯的亮度设置）
    buf[13] = (Brightness_H > 127) ? 127 : Brightness_H;
    // 最低亮度设置
    buf[14] = Brightness_Lowest;
    // 无人保持时间，即有人变成无人的延时时间，单位s
    buf[15] = DWORD_BYTE_DIVIDE_H4(CF_BrightHDelay);
    buf[16] = DWORD_BYTE_DIVIDE_H3(CF_BrightHDelay);
    // 中间亮度值设置，一般表示为检测到无人后的亮度
    buf[17] = Brightness_Middle;
    // 中间亮度保持时间，单位s
    buf[18] = DWORD_BYTE_DIVIDE_H4(Brightness_Middle_Delay_time);
    buf[19] = DWORD_BYTE_DIVIDE_H3(Brightness_Middle_Delay_time);

    // checksum 
    uint8_t checksum = 0; // 初始化校验和为0

    for(int i = 4; i < 7 ; i++)
    {
        checksum += buf[i];
    }
    for (int i = 8; i <= 19; i++) 
    {
        checksum += buf[i]; // 将每个元素的值累加到校验和中
    }
    buf[7] = DWORD_BYTE_DIVIDE_H4(checksum);

    if(FSL_UDP_SendData(socket_fd, buf, length, 0, client_addr, sizeof(struct sockaddr)) != 256)
    {
        printf("Send Buf: ");
        for(uint16_t i = 0; i < length; i++)
        {
            printf("%02X ", buf[i]);
        }
        printf("\n");
    }

}

// 【接收数据上报请求】
void FSL_Data_Report(char *buf)
{
    uint16_t short_adress = 0;
    if (buf[9] == 0x00 && buf[10] == 0x5E)
    {
        uint8_t hight_var = buf[5] & 0x0f;      // 取出该变量的低四位
        uint8_t low_var = buf[12];              // buf[12]是短地址的低字节
        short_adress = (hight_var << 8) | low_var;

        for(int i =0; i < sqlite3_check_table_columns(fsl_db, Device_List_Table); i ++)
        {
            // // 如果能找到设备列表里面的短地址，就把三段设置信息(停车场雷达设置协议)保存在该数组下标下面。
            // if(atoi(device_list_array[i].shortaddr) == short_adress)
            // {
            //     // 雷达感应开关，0表示关, 1表示开
            //     device_list_array[i].CF_RadarOnOff = buf[13];
            //     // 全亮模式的亮度值，亮度值为0-127对应0-100%(同灯的亮度设置)
            //     device_list_array[i].CF_BrightH = buf[14];
            //     // 最低亮度设置，表示长时间无人设置的亮度，同灯的亮度值设置
            //     device_list_array[i].CF_BrightL = buf[15];
            //     // 无人保持时间，即有人变成无人的延时时间，单位s
            //     device_list_array[i].CF_BrightHDelay = M_DWORD_WORD_COMBINE(buf[17], buf[16]);
            //     // 中间亮度值设置，一般表示为检测到无人后的亮度
            //     device_list_array[i].CF_BrightM = buf[18];
            //     // 中间亮度保持时间，单位s
            //     device_list_array[i].CF_BrightMDelay = M_DWORD_WORD_COMBINE(buf[20], buf[19]);
            // }
            uint8_t CF_RadarOnOff = buf[13];
            uint8_t CF_BrightH = buf[14];
            uint16_t CF_BrightHDelay = M_DWORD_WORD_COMBINE(buf[17], buf[16]);
            uint8_t CF_BrightM = buf[18];
            uint16_t CF_BrightMDelay = M_DWORD_WORD_COMBINE(buf[20], buf[19]);
            uint8_t CF_BrightL = buf[15];

            char short_address_str[6];
            snprintf(short_address_str, sizeof(short_address_str), "%u", short_adress);
            char sql[512];
            snprintf(sql, sizeof(sql), "UPDATE %s SET CF_RadarOnOff = %d, CF_BrightH = %d, CF_BrightHDelay = %d, CF_BrightM = %d, CF_BrightMDelay = %d, CF_BrightL = %d WHERE shortaddr = '%s';", 
                Device_List_Table, CF_RadarOnOff, CF_BrightH, CF_BrightHDelay, CF_BrightM, CF_BrightMDelay, CF_BrightL, short_address_str);
            int rc = sqlite3_exec(fsl_db, sql, 0, 0, 0);
            if (rc != SQLITE_OK)
            {
                fprintf(stderr, "[FSL_Data_Report] sqlite3_exec SQL error: %s\n", sqlite3_errmsg(fsl_db));
            }

        }
    }
}


// 【短地址控制请求】
void FSL_Short_Adress_Control(uint16_t Seq, struct sockaddr_in* client_addr, uint16_t short_adress, bool on_off, uint8_t brightness)
{
    uint16_t length = 7;        // 这个协议只需要7个字节 
    uint8_t buf[length];

    FSL_Handle_Protocol_head(Short_Address_Contral, Seq, buf);
    // 举例：假设short_adress是0x0102, 这里就会拆分为buf[4] = 0x02, buf[5] = 0x01
    buf[4] = DWORD_BYTE_DIVIDE_H4(short_adress);
    buf[5] = DWORD_BYTE_DIVIDE_H3(short_adress);    
    if(on_off)
    {
        if (brightness > MAX_BRIGHTNESS) 
        {
            brightness = MAX_BRIGHTNESS;
            // 将百分比转换为0-127范围内的值
            buf[6] = (brightness * 127) / MAX_BRIGHTNESS;
        }
        else if(brightness == 0)
        {
            buf[6] = 0x80;
        }
        else
        {
            buf[6] = (brightness * 127) / MAX_BRIGHTNESS;
        }
    }
    else
    {
        buf[6] = 0x00;
    }

    /* 符合实际协议的代码，暂时不用 */
    // if(brightness > 0)
    // {
    //     // 将百分比转换为0-127范围内的值
    //     brightness = (brightness * 127) / MAX_BRIGHTNESS;
    // }

    // if(on_off)
    // {
    //     buf[6] = 0x80 | brightness;
    // }
    // else
    // {
    //     buf[6] = brightness;
    // }

    if(FSL_UDP_SendData(socket_fd, buf, length, 0, client_addr, sizeof(struct sockaddr)) != 256)
    {
        printf("Send Buf: ");
        for(uint16_t i = 0; i < length; i++)
        {
            printf("%02X ", buf[i]);
        }
        printf("\n");
    }
}

// 触发单个设备状态上报请求
void FSL_Device_Status_Reporting(uint16_t Seq, struct sockaddr_in* client_addr, uint16_t short_adress)
{
    uint16_t length = 20;        // 这个协议需要20个字节 
    uint8_t buf[length];
    FSL_Handle_Protocol_head(Device_Status_Report, Seq, buf);

    // delay_max
    buf[4] = 0x00;
    // 短地址高4位
    buf[5] = DWORD_BYTE_DIVIDE_H3(short_adress);
    // 短地址低4位
    buf[6] = DWORD_BYTE_DIVIDE_H4(short_adress);
    uint8_t mask_buf[13] = {0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
    memcpy(buf + 7, mask_buf, sizeof(mask_buf));

    if(FSL_UDP_SendData(socket_fd, buf, length, 0, client_addr, sizeof(struct sockaddr)) != 256)
    {
        printf("Send Buf: ");
        for(uint16_t i = 0; i < length; i++)
        {
            printf("%02X ", buf[i]);
        }
        printf("\n");
    }
}


void FSL_Handle_Protocol_Data(uint16_t Type, uint16_t Seq, struct sockaddr_in* client_addr,  char *buf)
{
    // printf("Get Type = %04X \n", Type);
    // printf("Get Seq = %04X \n", Seq);

    pthread_mutex_lock(&protocol_mutex);
    global_client_addr = client_addr;

    switch (Type)
    {
        case HearBeat_Request:
            printf("【响应心跳请求】\n");
            FSL_HearBeat_Response(Seq, client_addr);                // 回复心跳
            // 上电的第一次就请求RUL，只请求一次
            if(FSL_Get_Url_Requested_Flag())
            {
                FSL_URL_Request(Seq, client_addr);                 
                FSL_Set_Url_File_Parse_Finish_Flag(false);
                FSL_Set_Url_Requested_Flag(false);
            }

            // 触发主动上报功能
            // FSL_Device_Status_Reporting(++Seq, client_addr, LIGHT1);

            // if(FSL_Get_Url_File_Parse_Finish_Flag())
            // {
            //     if(FSL_Get_Light_Switch_State())
            //     {
            //         FSL_All_Light_On_Off(++Seq, client_addr, 1, 50);

                    // FSL_Set_Park_Area_Sensor(++Seq, client_addr, LIGHT1, 
                    //                     0x02, 0, DWORD_BYTE_DIVIDE_H4(LIGHT1), 1, 
                    //                     50, 10, 0,  
                    //                     20, 10);

                //     FSL_Set_Light_Switch_State(0);
                // }
                // else
                // {
                //     FSL_All_Light_On_Off(++Seq, client_addr, 0, 0);

                    // FSL_Set_Park_Area_Sensor(++Seq, client_addr, LIGHT1, 
                    //                     0x02, 0, DWORD_BYTE_DIVIDE_H4(LIGHT1), 0, 
                    //                     50, 10, 0,  
                    //                     20, 10);

                //     FSL_Set_Light_Switch_State(1);
                // }            
            // }


            break;
        case URL_Response:
            if(FSL_URL_Response(buf) == EXIT_SUCCESS)
            {
                // 先清理数组
                FSL_Clear_Device_list();
                FSL_Clear_Sence_list();
                FSL_Clear_Family_Info();
                FSL_Parse_Url_File();
            }
            
            break;
        case Data_Report:
            FSL_Data_Report(buf);           // 目前只针对00 5e 做了数据存储, 005e是上报三段设置的属性

        default:
            break;

        
    }
    tmp_seq = Seq + 1000 + enter_thread_time;
    pthread_mutex_unlock(&protocol_mutex);


    return;
}



